<?php
//session_start();
//include_once("public.php");
include_once("../function.php");
//print_r($_GET);die;//Array ( [color] => #000000 [size] => XS [num] => 1 [id] => 147 [sub] => 加入购物车 )
extract($_GET);//$color $size $pid $num
$size=trim($size);
$num=trim($num);
$pid=trim($pid);
//1判断是否登录
if(!isset($_COOKIE["username"]))
{
	msg("尚未登录","./login.php");exit;
}
//2判断是否有商品加入
if(!isset($_GET["pid"]))
{
	msg("未选中商品","./index.php");exit;
}
//$id=$_GET["id"];
//判断是否有库存
$sql="select * from ts_product where pid=$pid";
$res=mysqli_query($link,$sql);
if(is_object($res))
{
	if(mysqli_num_rows($res)==1)
	{
		$one=mysqli_fetch_assoc($res);
		{
			if($one['snums']<1)
			{
				msg("该商品没有库存，请另选商品!","./index.php");exit;
			}
		}
	}
}
//4判断商品是否重复
//print_r($_COOKIE['username']);die;//wanmingming
$uname=$_COOKIE["username"];
$sql="select * from ts_user where username='$uname'";
//echo $sql;die;
$res1=mysqli_query($link,$sql);
if(is_object($res1))
{
	if(mysqli_num_rows($res)==1)
	{
		$one=mysqli_fetch_assoc($res1);
	}
	$sql="select * from ts_cart where user_id=".$one['uid'];
	//echo $sql;die;//select * from ts_cart where user_id=3
	$res=mysqli_query($link,$sql);
	if(is_object($res))
	{//var_dump(mysqli_num_rows($res));die;
		
		if(mysqli_num_rows($res)>0)
		{
			$car=array();
			while(($list=mysqli_fetch_assoc($res))!=false)
			{//echo 6;die;
				$car[]=$list;
				foreach($car as $v)
				{ //print_r($v['num']);die;
				}
				if($v['pid']==$pid&&$v['color']==$color&&$v['size']==$size)
				{
					$num=($v['num']+=$num);
					$sql="update ts_cart set num='$num' where pid='$pid' and color='$color' and size='$size'";
					$res=mysqli_query($link,$sql);
					if($res)
					{
						if(mysqli_affected_rows($link)==1)
						{
							msg("该商品已加入购物车","./shopcar.php");exit;
						}
					}
					
				 }
			}
		}
	}
}

//加入购物车
$uname=$_COOKIE["username"];
$sql="select * from ts_user where username='$uname'";
$res=mysqli_query($link,$sql);
if(is_object($res))
{
	if(mysqli_num_rows($res)==1)
	{
		$one=mysqli_fetch_assoc($res);
		//$a=$one['uid'];
		$sql="insert into ts_cart(color,size,num,user_id,pid) values('$color','$size','$num','$one[uid]','$pid')";
		$str=mysqli_query($link,$sql);
		//var_dump($str);die;
		if($str)
		{
			if(mysqli_affected_rows($link)==1)
			{
				msg("加入购物车成功","./shopcar.php");exit;
			}
		}
	}
}
?>